<?php

namespace App\Admin\Models;

use App\Admin\Traits\AdminUser;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\User as AuthUser;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class User extends AuthUser
{
    use AdminUser;

    protected $table = 'admin_users';

    protected $guarded = [];

    /**
     * On save make sure to set the default avatar if image is not set.
     */
    public function save(array $options = [])
    {
        // If no avatar has been set, set it to the default
        if (!$this->avatar) {
            $this->avatar = 'users/default.png';
        }

        parent::save();
    }

    public function getNameAttribute($value)
    {
        return ucwords($value);
    }

    public function getCreatedAtAttribute($value)
    {
        return Carbon::parse($value)->format('F jS, Y h:i A');
    }

    public function setCreatedAtAttribute($value)
    {
        $this->attributes['created_at'] = Carbon::parse($value)->format('Y-m-d H:i:s');
    }

    /*
     * 判断当前登录用户的权限
     * @author turtle
     * create_time 2017-01-15
     */

    public static function checkUserPermissions($check)
    {
        $user = Auth::user();
        $permission_ids = PermissionRole::getPermissionInfo($user['role_id']);
        $permissions = Permission::getPermissionSign($permission_ids);
        foreach ($permissions as $k => $permission) {
            $user_permissions[$k] = $permission['sign'];
        }
        if (!in_array($check, $user_permissions)) {
            return false;
        } else {
            return true;
        }

    }

    /**
     * @param $user 包含用户id,所在城市id,角色id
     * @return mixed|null
     * @Author 赵世伟
     * 获取用户的所有可能上级
     */
    public static function getSuperiors($user)
    {
        if (1 == $user['role_id']) {
            return null;
        }
        $roles = Role::where('id', $user['role_id'])->select('sup_id')->get();
        $role_where = array();
        $res = new User();
        if (!empty($roles)) {
            foreach ($roles as $role) {
                $role_where[] = $role['sup_id'];
            }
            $res = $res->whereIn('role_id', $role_where);
        }
        if (!empty($user['id'])) {
            $res = $res->where('id', '<>', $user['id']);
        }
        if (!empty($user['city']) && !in_array(1, $role_where)) {
            $res = $res->where('city', $user['city']);
        }

        $res = $res->select('id', 'name')->get();
        return json_decode(json_encode($res), true);
    }

    /**
     * @param $user 将要删除的用户
     * @param $operator 执行删除操作的用户
     * @return boolean
     * @Author 赵世伟
     * 检查用户是否有权限删除另外一个用户
     */
    public static function isAccessToDeleteUser($user, $operator)
    {
        if ($operator['id'] == 1) {
            if ($user['id'] == 1) {
                return false;
            } else {
                return true;
            }
        }
        if ($user['superior'] == $operator['id']) {//检查operator是否是user的上级
            return true;
        } else {
            if ($user['city'] != $operator['city']) {//检查operator和user是否是同一个城市
                return false;
            } else {
                $role_id = $operator['id'];
                $res = DB::select("select subUser($role_id) as users");
                $res = json_decode(json_encode($res), true);
                $res = explode(',', $res[0]["users"]);
                if (in_array($user['role_id'], $res) && $operator['id'] != $user['id']) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }

    public static function getNewUser($oldUser_id)
    {
        $oldUser = User::find($oldUser_id);
        $id = $oldUser['id'];
        $res = DB::select("select subUser($id) as users");
        $res = json_decode(json_encode($res), true);
        $res = explode(',', $res[0]["users"]);
        $newUsers = User::whereRaw("(city = ? and id <> ?) or id = 1",
            array(
                $oldUser['city'],
                $oldUser['id']
            ))->whereNotIn('role_id',$res)->get();

        return json_encode($newUsers);
    }
}
